from flask import Blueprint, jsonify, request
from app.forms import InitializeAdminForm, LoginForm
from secrets import token_hex
from app.exts import db
from werkzeug.security import generate_password_hash, check_password_hash
from app.models import UsersModel
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from utils import model_to_dict
from json import loads

auth = Blueprint('auth', __name__)


# 超级管理员初始化
@auth.post('/initialize/admin')
def initialize_admin():
    body_json = request.get_json()
    initialize_admin_form = InitializeAdminForm(data=body_json)
    # 表单验证不通过，进入该判断
    if not initialize_admin_form.validate():
        return jsonify({
            'code': 500,
            'data': None,
            'message': initialize_admin_form.errors['password'][0]
        })
    # 获取表单密码
    password = body_json['password']
    # 随机生成密码盐
    salt = token_hex(5)
    # 加盐后的密码
    salt_password = generate_password_hash(password + salt)
    admin_ORM = UsersModel.query.filter_by(username='admin').first()
    # 判断超级管理员是否存在，存在更改密码，不存在重新创建
    if admin_ORM:
        admin_ORM.password = salt_password
        admin_ORM.salt = salt
        db.session.commit()
    else:
        users_model = UsersModel(
            username='admin',
            password=salt_password,
            roles='["admin"]',
            salt=salt,
            avatar='https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            introduction='I am a super administrator',
            name='蜘蛛侠'
        )
        db.session.add(users_model)
        db.session.commit()
    return jsonify(code=200, data=None, message='初始化成功')


# 用户登录
@auth.post('/login')
def login():
    body_json = request.get_json()
    login_form = LoginForm(data=body_json)
    if not login_form.validate():
        # 只取出第一个错误信息并且发送给客户端
        error_first = next(iter(login_form.errors.values()))[0]
        return jsonify(code=400, message=error_first, data=None)
    username = body_json['username']
    password = body_json['password']
    user = UsersModel.query.filter_by(username=username).first()
    if not user:
        return jsonify(code=400, message='账号不存在', data=None)
    salt_password = password + user.salt
    if not check_password_hash(user.password, salt_password):
        return jsonify(code=400, message='账号或者密码错误', data=None)
    token = create_access_token(identity={'user_id': user.id})
    return jsonify(code=200, message='登录成功', data={'token': token})


# 获取用户基本信息
@auth.get('/info')
@jwt_required()
def info():
    id = get_jwt_identity().get('user_id')
    user_ORM = UsersModel.query.get(id)
    user = model_to_dict(user_ORM)
    user.pop('password')
    user.pop('salt')
    user['roles'] = loads(user['roles'])
    return jsonify(code=200, message='获取成功', data=user)
